<template>
  <div class="record-detail">
    <van-nav-bar
      :title="`练习详情 - ${record.categoryName || '未知分类'}`"
      left-text="返回"
      left-arrow
      fixed
      @click-left="$router.go(-1)"
    />
    
    <div class="content-wrapper">
      <!-- 加载状态 -->
      <van-loading v-if="loading" size="24px" vertical>加载中...</van-loading>
      
      <!-- 错误提示 -->
      <van-empty v-else-if="error" :description="error" image="error">
        <van-button round type="primary" @click="fetchRecordDetails">重试</van-button>
      </van-empty>
      
      <!-- 内容区域 -->
      <template v-else>
        <!-- 顶部统计卡片 -->
        <div class="summary-card">
          <div class="summary-item">
            <div class="summary-icon">
              <van-icon name="medal" color="#1989fa" />
            </div>
            <div class="summary-content">
              <div class="summary-label">得分</div>
              <div class="summary-value score">{{ record.score }}分</div>
            </div>
          </div>
          
          <div class="summary-item">
            <div class="summary-icon">
              <van-icon name="passed" color="#07c160" />
            </div>
            <div class="summary-content">
              <div class="summary-label">正确率</div>
              <div class="summary-value">{{ correctRate }}%</div>
            </div>
          </div>
          
          <div class="summary-item">
            <div class="summary-icon">
              <van-icon name="clock" color="#ff976a" />
            </div>
            <div class="summary-content">
              <div class="summary-label">用时</div>
              <div class="summary-value" id="record-duration">{{ formatDuration(record.duration) }}</div>
            </div>
          </div>
        </div>
        
        <!-- 练习时间信息 -->
        <div class="time-card">
          <van-icon name="underway" color="#1989fa" size="16" />
          <span class="time-text">{{ record.startTime }} -- {{ record.endTime }}</span>
        </div>
        
        <!-- 题目列表 -->
        <div class="questions-container">
          <div 
            v-for="(detail, index) in questionDetails" 
            :key="detail.id"
            class="question-card"
            :class="{ 'correct-card': detail.isCorrect === 1, 'wrong-card': detail.isCorrect === 0 }"
          >
            <div class="question-header">
              <div class="question-number">
                <span class="number-circle">{{ index + 1 }}</span>
                <span class="question-status" :class="detail.isCorrect === 1 ? 'correct-text' : 'wrong-text'">
                  {{ detail.isCorrect === 1 ? '正确' : '错误' }}
                </span>
              </div>
              <van-tag 
                :type="detail.isCorrect === 1 ? 'success' : 'danger'" 
                size="medium"
                round
              >
                {{ detail.isCorrect === 1 ? '✓' : '✗' }}
              </van-tag>
            </div>
            
            <div class="question-content-box">
              <div class="question-content">{{ detail.content }}</div>
              
              <!-- 选择题选项 -->
              <div v-if="[1, 2].includes(detail.questionType)" class="question-options">
                <div 
                  v-for="(option, key) in parseOptions(detail.options)" 
                  :key="key"
                  class="option-item"
                  :class="{
                    'correct-option': isCorrectOption(key, detail.correctAnswer),
                    'user-selected': isUserSelected(key, detail.userAnswer) && detail.isCorrect === 0
                  }"
                >
                  <span class="option-key">{{ key }}.</span>
                  <span class="option-value">{{ option }}</span>
                </div>
              </div>
              
              <!-- 判断题 -->
              <div v-if="detail.questionType === 3" class="judge-options">
                <div 
                  class="option-item"
                  :class="{
                    'correct-option': detail.correctAnswer === '1',
                    'user-selected': detail.userAnswer === '1' && detail.isCorrect === 0
                  }"
                >
                  <span class="option-key">正确</span>
                </div>
                <div 
                  class="option-item"
                  :class="{
                    'correct-option': detail.correctAnswer === '0',
                    'user-selected': detail.userAnswer === '0' && detail.isCorrect === 0
                  }"
                >
                  <span class="option-key">错误</span>
                </div>
              </div>
              
              <!-- 填空题答案 -->
              <div v-if="detail.questionType === 4" class="fill-blank-answer">
                <div class="blank-item">
                  <span class="blank-label">你的答案:</span>
                  <span class="blank-value user-answer">{{ detail.userAnswer || '未作答' }}</span>
                </div>
                <div class="blank-item">
                  <span class="blank-label">正确答案:</span>
                  <span class="blank-value correct-answer">{{ detail.correctAnswer }}</span>
                </div>
              </div>
            </div>
            
            <!-- 非填空题的答案显示 -->
            <div v-if="detail.questionType !== 4" class="answer-container">
              <div class="answer-row">
                <div class="answer-label">你的答案:</div>
                <div class="user-answer" :class="{ 'correct-answer': detail.isCorrect === 1 }">
                  {{ formatUserAnswer(detail) }}
                </div>
              </div>
              <div class="answer-row">
                <div class="answer-label">正确答案:</div>
                <div class="correct-answer">
                  {{ formatCorrectAnswer(detail) }}
                </div>
              </div>
            </div>
            
            <div class="explanation-box" v-if="detail.explanation">
              <div class="explanation-header">
                <van-icon name="info" color="#07c160" size="14" />
                <span class="explanation-title">题目解析</span>
              </div>
              <div class="explanation-content">{{ detail.explanation }}</div>
            </div>
          </div>
        </div>
        
        <!-- 底部操作栏 -->
       <!--  <div class="action-bar">
          <van-button 
            round 
            type="primary" 
            size="large"
            @click="redoPractice"
            class="redo-button"
          >
            <van-icon name="replay" size="16" />
            <span>重新练习</span>
          </van-button>
        </div> -->
      </template>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { getPracticeRecordDetails,getPracticeRecordByRecordNo } from '@/api/record';
import { showToast } from 'vant';

const route = useRoute();
const router = useRouter();

// 状态管理
const loading = ref(false);
const error = ref(''); // 错误
//记录详情
const record = ref({
  recordNo: '',
  categoryName: '',
  score: 0,
  correctCount: 0,
  totalQuestions: 0,
  duration: 0,
  startTime: '',
  endTime: ''
});
// 题目详情
const questionDetails = ref<any[]>([]);

// 计算正确率
const correctRate = computed(() => {
  if (record.value.totalQuestions === 0) return 0;
  return Math.round((record.value.correctCount / record.value.totalQuestions) * 100);
});
/*******************************
 * @description: 获取答题记录详情
 * 发送请求获取响应结果
 * 根据响应结果更新状态
 * 解析选项JSON
 * 判断是否是正确答案
 * 判断是否是用户选择的错误答案
 * 格式化用户答案
 */
// 获取完整的答题记录详情
const fetchRecordDetails = async () => {
  try {
    loading.value = true;
    error.value = '';
    const recordNo = route.params.recordNo as string;
    
    const res = await getPracticeRecordDetails(recordNo);
    const res2 = await getPracticeRecordByRecordNo(recordNo);
    if (res.data.code === 200) {
      // 处理记录基本信息
      const details = res.data.data;
      const practiceRecord =  res2.data.data;
      if (details && details.length > 0) {
        record.value = {
          recordNo: details[0].recordNo,
          categoryName: details[0].categoryName || '未知分类',
          score: calculateScore(details),
          correctCount: details.filter((d: any) => d.isCorrect === 1).length,
          totalQuestions: details.length,
          duration: practiceRecord.duration,
          startTime: practiceRecord.startTime,
          endTime: practiceRecord.endTime // 实际项目中应该有单独的结束时间字段
        };
        questionDetails.value = details;
      }
    } else {
      throw new Error(res.data.message || '获取详情失败');
    }
  } catch (err: any) {
    error.value = err.message || '加载详情失败，请稍后重试';
    console.error('获取记录详情失败:', err);
  } finally {
    loading.value = false;
  }
};

// 计算得分
const calculateScore = (details: any[]) => {
  const correctCount = details.filter(d => d.isCorrect === 1).length;
  return Math.round((correctCount / details.length) * 100);
};


// 解析选项JSON
const parseOptions = (optionsStr: string) => {
  try {
    return optionsStr ? JSON.parse(optionsStr) : {};
  } catch (e) {
    console.error('解析选项失败:', e);
    return {};
  }
};

// 判断是否是正确答案
const isCorrectOption = (key: string, correctAnswer: string) => {
  if (!correctAnswer) return false;
  return correctAnswer.split(',').includes(key);
};

// 判断是否是用户选择的错误答案
const isUserSelected = (key: string, userAnswer: string) => {
  if (!userAnswer) return false;
  return userAnswer.split(',').includes(key);
};

// 格式化用户答案
const formatUserAnswer = (detail: any) => {
  if ([1, 2].includes(detail.questionType)) {
    // 单选或多选
    return detail.userAnswer?.split(',').map((a: string) => a.trim()).join(', ') || '未作答';
  } else if (detail.questionType === 3) {
    // 判断题
    return detail.userAnswer === '1' ? '正确' : detail.userAnswer === '0' ? '错误' : '未作答';
  }
  return detail.userAnswer || '未作答';
};

// 格式化正确答案
const formatCorrectAnswer = (detail: any) => {
  if ([1, 2].includes(detail.questionType)) {
    // 单选或多选
    return detail.correctAnswer?.split(',').map((a: string) => a.trim()).join(', ');
  } else if (detail.questionType === 3) {
    // 判断题
    return detail.correctAnswer === '1' ? '正确' : '错误';
  }
  return detail.correctAnswer;
};

// 格式化时间
const formatDuration = (seconds: number) => {
  const mins = Math.floor(seconds / 60);
  const secs = seconds % 60;
  return `${mins}分${secs}秒`;
};

// 格式化日期时间
const formatDateTime = (datetime: string) => {
  if (!datetime) return '';
  const date = new Date(datetime);
  const hours = date.getHours().toString().padStart(2, '0');
  const minutes = date.getMinutes().toString().padStart(2, '0');
  return `${hours}:${minutes}`;
};

// 重新练习
const redoPractice = () => {
  if (!record.value.categoryName) {
    showToast('无法确定分类');
    return;
  }
  router.push({ 
    name: 'Practice', 
    query: { category: record.value.categoryName }
  });
};

onMounted(() => {
  fetchRecordDetails();
});
</script>

<style scoped>
.record-detail {
  padding-top: 10px;
  padding-bottom: 80px;
  min-height: 100vh;
  background-color: #f7f8fa;
}
#record-duration{
  font-size: 14px;
}

.content-wrapper {
  padding: 0 12px;
}

/* 统计卡片样式 */
.summary-card {
  display: flex;
  justify-content: space-between;
  background: white;
  border-radius: 12px;
  padding: 16px;
  margin: 12px 0;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.06);
}

.summary-item {
  display: flex;
  align-items: center;
  flex: 1;
}

.summary-icon {
  margin-right: 10px;
  background-color: #f0f7ff;
  width: 36px;
  height: 36px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
}

.summary-content {
  display: flex;
  flex-direction: column;
}

.summary-label {
  font-size: 12px;
  color: #969799;
  margin-bottom: 2px;
}

.summary-value {
  font-size: 18px;
  font-weight: bold;
}

.score {
  color: #1989fa;
}

/* 时间卡片样式 */
.time-card {
  background: white;
  border-radius: 8px;
  padding: 12px;
  margin-bottom: 12px;
  display: flex;
  align-items: center;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.05);
}

.time-text {
  margin-left: 8px;
  font-size: 13px;
  color: #323233;
}

/* 题目卡片样式 */
.questions-container {
  margin-bottom: 20px;
}

.question-card {
  background-color: white;
  border-radius: 12px;
  padding: 16px;
  margin-bottom: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  transition: transform 0.2s;
}

.question-card:active {
  transform: scale(0.98);
}

.correct-card {
  border-left: 4px solid #07c160;
}

.wrong-card {
  border-left: 4px solid #ee0a24;
}

.question-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
}

.question-number {
  display: flex;
  align-items: center;
}

.number-circle {
  width: 24px;
  height: 24px;
  background-color: #1989fa;
  color: white;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 12px;
  margin-right: 8px;
}

.question-status {
  font-size: 14px;
  font-weight: 500;
}

.correct-text {
  color: #07c160;
}

.wrong-text {
  color: #ee0a24;
}

.question-content-box {
  margin-bottom: 16px;
}

.question-content {
  font-size: 15px;
  line-height: 1.6;
  color: #323233;
}

/* 选择题选项样式 */
.question-options {
  margin-top: 12px;
}

.option-item {
  padding: 8px 12px;
  margin: 4px 0;
  border-radius: 6px;
  background-color: #f7f8fa;
  font-size: 14px;
  line-height: 1.5;
}

.correct-option {
  background-color: #f0f9eb;
  color: #07c160;
  font-weight: 500;
}

.user-selected {
  background-color: #fef0f0;
  color: #ee0a24;
  font-weight: 500;
}

.option-key {
  font-weight: bold;
  margin-right: 8px;
}

/* 填空题样式 */
.fill-blank-answer {
  margin-top: 12px;
}

.blank-item {
  display: flex;
  align-items: center;
  margin: 6px 0;
}

.blank-label {
  font-size: 13px;
  color: #969799;
  min-width: 70px;
}

.blank-value {
  font-size: 14px;
  font-weight: 500;
}

/* 答案容器样式 */
.answer-container {
  background-color: #f7f8fa;
  border-radius: 8px;
  padding: 12px;
  margin-bottom: 12px;
}

.answer-row {
  display: flex;
  margin-bottom: 8px;
}

.answer-row:last-child {
  margin-bottom: 0;
}

.answer-label {
  font-size: 13px;
  color: #969799;
  min-width: 70px;
}

.user-answer {
  font-size: 14px;
  color: #1989fa;
  font-weight: 500;
}

.correct-answer {
  font-size: 14px;
  color: #07c160;
  font-weight: 500;
}

/* 解析框样式 */
.explanation-box {
  background-color: #f0f9eb;
  border-radius: 8px;
  padding: 12px;
  margin-top: 12px;
}

.explanation-header {
  display: flex;
  align-items: center;
  margin-bottom: 6px;
}

.explanation-title {
  font-size: 13px;
  color: #07c160;
  font-weight: 500;
  margin-left: 6px;
}

.explanation-content {
  font-size: 13px;
  color: #323233;
  line-height: 1.5;
}

/* 底部操作栏 */
.action-bar {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  padding: 12px;
  background-color: white;
  box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.05);
  z-index: 100;
}

.redo-button {
  width: 100%;
  height: 44px;
  font-size: 16px;
}

.redo-button .van-icon {
  margin-right: 6px;
}
</style>